<template>
  <div class="addPersonnel-container-padding">
    <div v-if="!isHidden" class="buttonList">
      <el-button type="primary" @click="save">保存为草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <el-form
      :model="formInline"
      class="form-inline"
      label-width="auto"
      label-position="top"
      ref="addForm"
    >
      <el-form-item
        v-for="(item, index) in addFormList"
        :key="index"
        :label="item.label"
      >
        <!-- input -->
        <el-input
          v-if="item.type === 'input'"
          v-model="formInline[item.prop]"
          placeholder="请输入"
          clearable
        />
        <!-- select -->
        <el-select
          v-if="item.type === 'select'"
          v-model="formInline[item.prop]"
          placeholder="请选择"
        >
          <el-option
            v-for="j in item.options"
            :key="j.value"
            :label="j.label"
            :value="j.value"
          />
        </el-select>

        <!-- textarea -->
        <el-input
          v-if="item.type === 'textarea'"
          v-model="formInline[item.prop]"
          placeholder="请输入"
          :rows="4"
          type="textarea"
          clearable
        />
      </el-form-item>
    </el-form>
    <div>
      <p>五、标准主要编写成员姓名、职称、工作单位</p>
      <vxe-grid
        ref="xGrid"
        v-bind="addGridOptions"
        :height="height"
        style="width: 100%"
      >
        <template #operate="{ row }">
          <template v-if="hasActiveEditRow(row)">
            <vxe-button content="取消" />
            <vxe-button
              status="primary"
              content="保存"
              @click="saveRowEvent(row)"
            />
          </template>
          <template v-else>
            <vxe-button content="编辑" @click="editRowEvent(row)" />
          </template>
          <vxe-button
            status="danger"
            content="删除"
            @click="removeRowEvent(row)"
          />
        </template>
        <template #patentName_edit="{ row }">
          <vxe-input v-model="row.patentName" />
        </template>
        <template #patentPhone_edit="{ row }">
          <vxe-input v-model="row.patentPhone" />
        </template>
        <template #patentType_edit="{ row }">
          <vxe-input v-model="row.patentType" />
        </template>
      </vxe-grid>
      <el-button type="primary" text :icon="Plus" @click="addInventor">
        增加成员
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, defineProps, withDefaults, onMounted } from 'vue'
  import { Delete, Plus } from '@element-plus/icons-vue'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { addFormList, addGridOptions } from '../table/column'
  import { getSimpleDeptList } from '@/api/system/dept'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import {
    getEnterpriseInfo,
    addEnterprise,
    updateEnterprise,
  } from '@/api/standard/amendment'
  import { useRoute } from 'vue-router'
  import { VXETable } from 'vxe-table'
  import { useDictStore } from '@/store/modules/dict'
  const dictStore = useDictStore()
  const { closeTabNavigate } = useCloseTabNavigate()
  const route = useRoute()
  const addForm = ref()

  const props = withDefaults(
    defineProps<{
      disabled?: boolean
      isHidden?: boolean
    }>(),
    {
      disabled: false,
      isHidden: false,
    }
  )
  const getDptList = () => {
    getSimpleDeptList().then((res: any) => {
      const list = []
      res.data.forEach((item) => {
        list.push({
          label: item.name,
          value: item.id,
        })
      })
      store.setDeptList(list)
      return list
    })
  }

  const store = useAchievementAwardStore()
  const { DeptList } = storeToRefs(store)
  const departmentOptions = computed((): any => {
    return DeptList.value.length == 0 ? getDptList() : DeptList.value
  })

  const validProps = new Set([
    'status',
    'standardType',
    'belongProfession',
    'draftUnitId',
  ])
  const propToOptionsMap = {
    status: computed(() =>
      dictStore.getDictType('enterprise_standard_flow_status')
    ),
    standardType: [],
    belongProfession: [],
    draftUnitId: departmentOptions,
  }

  addFormList.value.forEach((item) => {
    if (validProps.has(item.prop)) {
      item.options = propToOptionsMap[item.prop]
    }
  })

  const formInline = ref({
    writingMembers: '',
    draftUnitName: '',
    draftUnitId: undefined,
  })
  const xGrid = ref()
  // 保存为草稿
  const save = async () => {
    try {
      const { tableData } = xGrid.value.getTableData()
      formInline.value.writingMembers = JSON.stringify(tableData)
      formInline.value.draftUnitName = departmentOptions.value.find(
        (item) => item.value == formInline.value.draftUnitId
      ).label
      const params = {
        id: route.query.id || '',
        type: 'STANDARD_PROJECT_REPORT',
        submitJson: JSON.stringify({
          ...formInline.value,
          draftBoxId: route.query?.id || '',
        }),
      }
      const res: any = await postDraftBoxCreate(params)
      if (res && res.code === 0) {
        ElMessage.success('保存草稿成功')
        addForm.value.resetFields()
        closeTabNavigate({ name: 'Amendment' })
      } else {
        ElMessage.error(`保存草稿失败: ${res.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('保存草稿失败', e)
    }
  }
  // 提交表单
  const submit = async () => {
    addForm.value.validate(async (valid: boolean) => {
      if (valid) {
        const { tableData } = xGrid.value.getTableData()
        formInline.value.writingMembers = JSON.stringify(tableData)
        formInline.value.draftUnitName = departmentOptions.value.find(
          (item) => item.value == formInline.value.draftUnitId
        ).label
        let params = {
          ...formInline.value,
        }
        params.draftUnitId = formInline.value.draftUnitId.toString()
        addEnterprise(params).then((res: any) => {
          let { code } = res
          if (code == 0) {
            ElMessage.success('新增成功')
            closeTabNavigate({ name: 'Amendment' })
          }
        })
      }
    })
  }

  const hasActiveEditRow = (row: any) => {
    const $grid = xGrid.value
    if ($grid) {
      return $grid.isEditByRow(row)
    }
    return false
  }

  const editRowEvent = (row: any) => {
    const $grid = xGrid.value
    if ($grid) {
      $grid.setEditRow(row)
    }
  }

  const saveRowEvent = async (row: any) => {
    const $grid = xGrid.value
    if ($grid) {
      await $grid.clearEdit()
      // 模拟异步保存
    }
  }

  const removeRowEvent = async (row: any) => {
    const $grid = xGrid.value
    const type = await VXETable.modal.confirm('您确定要删除该数据?')
    if ($grid) {
      if (type === 'confirm') {
        await $grid.remove(row)
      }
    }
  }
  const addInventor = () => {
    const $grid = xGrid.value
    $grid.insert({})
  }

  onMounted(() => {
    let id = route.query.id
    let getType = route.query.getType ?? 2
    if (id) {
      getEnterpriseInfo({ id, getType }).then((res: any) => {
        let { code, data } = res
        if (code == 0) {
          formInline.value = data || {}
          addGridOptions.data = JSON.parse(formInline.value.writingMembers)
        }
      })
    }
  })

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const height = ref(0)
  const $baseTableHeight = inject<any>('$baseTableHeight')
  onBeforeMount(() => {
    window.addEventListener('resize', handleHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleHeight)
  })

  const handleHeight = () => {
    height.value = $baseTableHeight(0)
  }
</script>

<style scoped lang="scss">
  $margin-bottom: 20px;
  .margin-left20 {
    margin-left: $margin-bottom;
  }
  .buttonList {
    display: flex;
    justify-content: end;
    padding-bottom: $margin-bottom;
    border-bottom: 1px solid #edeff2;
    margin-bottom: $margin-bottom;
  }
  .card {
    .title {
      border-radius: 2px;
      border-left: 5px solid #1890ff;
      height: 28px;
      background: #f7f8f9;
      font-weight: 500;
      font-size: 14px;
      color: #606266;
      padding-left: 12px;
      line-height: 28px;
      margin-bottom: $margin-bottom;
    }
  }

  .margin-bottom0 {
    margin-bottom: 0 !important;
  }

  .margin-top20 {
    margin-top: 20px;
  }

  .demo-form-inline {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;
    .el-input {
      // --el-input-width: 323px;
    }
    .el-select {
      // --el-select-width: 323px;
    }
    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .flexBox {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column-gap: 20px;
  }

  .formCard {
    border-radius: 4px;
    .formCardtitle {
      background: #e7f3ff;
      font-size: 12px;
      color: #7d8398;
      padding-left: 10px;
      height: 24px;
      line-height: 24px;
      border-radius: 4px 4px 0 0;
    }
    .cardForm {
      background: #f6fbff;
      padding: 20px;
      border-radius: 0 0 4px 4px;
      .el-input {
        // --el-input-width: 421px;
      }
    }
  }

  .demo-form {
    :deep(.el-form-item__content) {
      display: block;
    }
    .el-input {
      --el-input-width: 50%;
    }

    .el-select {
      --el-select-width: 50%;
    }
  }
  .last {
    margin-top: $margin-bottom;
  }

  .form-inline {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;
  }
</style>
